package org.example.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.dromara.easyes.core.biz.EsPageInfo;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.example.entity.FaultInstanceEsEntity;
import org.example.mapper.FaultInstanceEsMapper;
import org.example.service.IElasticSearchService;
import org.example.utils.EmbeddingUtil;
import org.example.utils.EsQueryUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ElasticSearchServiceImpl implements IElasticSearchService {
    private static final float scoreLimit = 5.0f;
    @Resource
    private FaultInstanceEsMapper faultInstanceEsMapper;


    @Override
    public void search(String text) {
        double[] vector = EmbeddingUtil.getEmbedding(text);
        log.info("vector: {}", vector);

        LambdaEsQueryWrapper<FaultInstanceEsEntity> wrapper = new LambdaEsQueryWrapper<>();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder
                .should(QueryBuilders.multiMatchQuery(text,
                        "faultPhenomenonDescription",
                        "faultReasonAnalyze",
                        "faultRepairContent"))
                .should(EsQueryUtils.vectorQuery("faultPhenomenonDescriptionVector", vector))
                .should(EsQueryUtils.vectorQuery("faultReasonAnalyzeVector", vector))
                .should(EsQueryUtils.vectorQuery("faultRepairContentVector", vector));
        boolQueryBuilder.minimumShouldMatch(1); // 确保至少一个 should 匹配
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.minScore(scoreLimit);
        // 添加按 _score 倒序排序
        searchSourceBuilder.sort("_score", SortOrder.DESC);
        wrapper.setSearchSourceBuilder(searchSourceBuilder);
        EsPageInfo<FaultInstanceEsEntity> esPageInfo = faultInstanceEsMapper.pageQuery(wrapper, 1, 10);
        List<Float> collect = esPageInfo.getList().stream().map(FaultInstanceEsEntity::getScore).collect(Collectors.toList());
        log.info("collect: {}", collect);
    }
}
